package model;

import java.sql.*;

//在这里实现用户登录功能  用户注册功能
public class UserDao {

    //根据用户名在数据库中查找，如果有则返回这一条数据
    public User selectByUserName(String username){

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;


        try {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            //1.与数据库建立连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/taobao","root","dddd");
            System.out.println("连接成功");
            //2.根据username在数据库中查询数据
            String sql = "select * from user where username = ? ";
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                //3.将查询到的数据通过user对象返回
                return user;
            }



        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return null;

    }




}
